<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>RabbitMQ | 阿毛的博客</title><meta name="keywords" content="RabbitMq"><meta name="author" content="myl"><meta name="copyright" content="myl"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="0. 学习目标 能够说出什么是消息中间件 能够安装RabbitMQ 能够编写RabbitMQ的入门程序 能够说出RabbitMQ的5种模式特征 能够使用Spring整合RabbitMQ  1. 消息中间件概述1.1. 什么是消息中间件MQ全称为Message Queue，消息队列是应用程序和应用程序之间的通信方法。  为什么使用MQ 在项目中，可将一些无需即时返回且耗时的操作提取出来，进行异步处理">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ">
<meta property="og:url" content="https://gitee.com/tgreen/myl-mm.git/2022/05/09/RabbitMQ%20%E8%AE%B2%E4%B9%89/index.html">
<meta property="og:site_name" content="阿毛的博客">
<meta property="og:description" content="0. 学习目标 能够说出什么是消息中间件 能够安装RabbitMQ 能够编写RabbitMQ的入门程序 能够说出RabbitMQ的5种模式特征 能够使用Spring整合RabbitMQ  1. 消息中间件概述1.1. 什么是消息中间件MQ全称为Message Queue，消息队列是应用程序和应用程序之间的通信方法。  为什么使用MQ 在项目中，可将一些无需即时返回且耗时的操作提取出来，进行异步处理">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg">
<meta property="article:published_time" content="2022-05-09T09:01:43.985Z">
<meta property="article:modified_time" content="2022-05-09T11:33:54.201Z">
<meta property="article:author" content="myl">
<meta property="article:tag" content="RabbitMq">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg"><link rel="shortcut icon" href="/myl-mm/img/favicon.png"><link rel="canonical" href="https://gitee.com/tgreen/myl-mm.git/2022/05/09/RabbitMQ%20%E8%AE%B2%E4%B9%89/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/myl-mm/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/myl-mm/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'RabbitMQ',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-09 19:33:54'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/myl-mm/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/myl-mm/tags/"><div class="headline">标签</div><div class="length-num">11</div></a><a href="/myl-mm/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myl-mm/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/myl-mm/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/myl-mm/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/long1.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/myl-mm/">阿毛的博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myl-mm/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/myl-mm/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/myl-mm/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">RabbitMQ</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-09T09:01:43.985Z" title="发表于 2022-05-09 17:01:43">2022-05-09</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-09T11:33:54.201Z" title="更新于 2022-05-09 19:33:54">2022-05-09</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/myl-mm/categories/RabbitMq/">RabbitMq</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="RabbitMQ"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="0-学习目标"><a href="#0-学习目标" class="headerlink" title="0. 学习目标"></a>0. 学习目标</h1><ul>
<li>能够说出什么是消息中间件</li>
<li>能够安装RabbitMQ</li>
<li>能够编写RabbitMQ的入门程序</li>
<li>能够说出RabbitMQ的5种模式特征</li>
<li>能够使用Spring整合RabbitMQ</li>
</ul>
<h1 id="1-消息中间件概述"><a href="#1-消息中间件概述" class="headerlink" title="1. 消息中间件概述"></a>1. 消息中间件概述</h1><h2 id="1-1-什么是消息中间件"><a href="#1-1-什么是消息中间件" class="headerlink" title="1.1. 什么是消息中间件"></a>1.1. 什么是消息中间件</h2><p>MQ全称为Message Queue，消息队列是应用程序和应用程序之间的通信方法。</p>
<ul>
<li><p>为什么使用MQ</p>
<p>在项目中，可将一些无需即时返回且耗时的操作提取出来，进行<strong>异步处理</strong>，而这种异步处理的方式大大的节省了服务器的请求响应时间，从而<strong>提高</strong>了<strong>系统</strong>的<strong>吞吐量</strong>。</p>
</li>
<li><p>开发中消息队列通常有如下应用场景：</p>
<p>1、任务<strong>异步</strong>处理</p>
<p>将不需要同步处理的并且耗时长的操作由消息队列通知消息接收方进行异步处理。提高了应用程序的响应时间。</p>
<p>2、应用程序<strong>解耦合</strong></p>
<p>MQ相当于一个中介，生产方通过MQ与消费方交互，它将应用程序进行解耦合。</p>
<p>3、<strong>削峰填谷</strong></p>
<p>如订单系统，在下单的时候就会往数据库写数据。但是数据库只能支撑每秒1000左右的并发写入，并发量再高就容易宕机。低峰期的时候并发也就100多个，但是在高峰期时候，并发量会突然激增到5000以上，这个时候数据库肯定卡死了。</p>
<p><img src="/myl-mm/assets/01.jpg"></p>
<p>消息被MQ保存起来了，然后系统就可以按照自己的消费能力来消费，比如每秒1000个数据，这样慢慢写入数据库，这样就不会卡死数据库了。</p>
<p><img src="/myl-mm/assets/02.jpg"></p>
<p>但是使用了MQ之后，限制消费消息的速度为1000，但是这样一来，高峰期产生的数据势必会被积压在MQ中，高峰就被“削”掉了。但是因为消息积压，在高峰期过后的一段时间内，消费消息的速度还是会维持在1000QPS，直到消费完积压的消息,这就叫做“填谷”</p>
<p><img src="/myl-mm/assets/03.jpg"></p>
</li>
</ul>
<h2 id="1-2-AMQP-和-JMS"><a href="#1-2-AMQP-和-JMS" class="headerlink" title="1.2. AMQP 和 JMS"></a>1.2. AMQP 和 JMS</h2><p>MQ是消息通信的模型；实现MQ的大致有两种主流方式：AMQP、JMS。</p>
<h3 id="1-2-1-AMQP"><a href="#1-2-1-AMQP" class="headerlink" title="1.2.1. AMQP"></a>1.2.1. AMQP</h3><p>AMQP是一种协议，更准确的说是一种binary wire-level protocol（链接协议）。这是其和JMS的本质差别，AMQP不从API层进行限定，而是直接定义网络交换的数据格式。</p>
<h3 id="1-2-2-JMS"><a href="#1-2-2-JMS" class="headerlink" title="1.2.2. JMS"></a>1.2.2. JMS</h3><p>JMS即Java消息服务（JavaMessage Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的API，用于在两个应用程序之间，或分布式系统中发送消息，进行异步通信。</p>
<h3 id="1-2-3-AMQP-与-JMS-区别"><a href="#1-2-3-AMQP-与-JMS-区别" class="headerlink" title="1.2.3. AMQP 与 JMS 区别"></a>1.2.3. AMQP 与 JMS 区别</h3><ul>
<li>JMS是定义了统一的接口，来对消息操作进行统一；AMQP是通过规定协议来统一数据交互的格式</li>
<li>JMS限定了必须使用Java语言；AMQP只是协议，不规定实现方式，因此是跨语言的。</li>
<li>JMS规定了两种消息模式；而AMQP的消息模式更加丰富</li>
</ul>
<h2 id="1-3-消息队列产品"><a href="#1-3-消息队列产品" class="headerlink" title="1.3. 消息队列产品"></a>1.3. 消息队列产品</h2><p>市场上常见的消息队列有如下：</p>
<ul>
<li>ActiveMQ：基于JMS</li>
<li>ZeroMQ：基于C语言开发</li>
<li>RabbitMQ：基于AMQP协议，erlang语言开发，稳定性好</li>
<li>RocketMQ：基于JMS，阿里巴巴产品</li>
<li>Kafka：类似MQ的产品；分布式消息系统，高吞吐量</li>
</ul>
<h2 id="1-4-RabbitMQ"><a href="#1-4-RabbitMQ" class="headerlink" title="1.4. RabbitMQ"></a>1.4. RabbitMQ</h2><p>RabbitMQ是由erlang语言开发，基于AMQP（Advanced Message Queue 高级消息队列协议）协议实现的消息队列，它是一种应用程序之间的通信方法，消息队列在分布式系统开发中应用非常广泛。</p>
<p>RabbitMQ官方地址：<a target="_blank" rel="noopener" href="http://www.rabbitmq.com/">http://www.rabbitmq.com/</a></p>
<p>RabbitMQ提供了6种模式：简单模式，work模式，Publish&#x2F;Subscribe发布与订阅模式，Routing路由模式，Topics主题模式，RPC远程调用模式（远程调用，不太算MQ；暂不作介绍）；</p>
<p>官网对应模式介绍：<a target="_blank" rel="noopener" href="https://www.rabbitmq.com/getstarted.html">https://www.rabbitmq.com/getstarted.html</a></p>
<p><img src="/myl-mm/assets/1555988678324.png" alt="1555988678324"></p>
<h1 id="2-安装及配置RabbitMQ"><a href="#2-安装及配置RabbitMQ" class="headerlink" title="2. 安装及配置RabbitMQ"></a>2. 安装及配置RabbitMQ</h1><p>详细查看 <code>资料/软件/安装RabbitMQ.md</code> 文档。</p>
<h1 id="3-RabbitMQ入门"><a href="#3-RabbitMQ入门" class="headerlink" title="3. RabbitMQ入门"></a>3. RabbitMQ入门</h1><h2 id="3-1-搭建示例工程"><a href="#3-1-搭建示例工程" class="headerlink" title="3.1. 搭建示例工程"></a>3.1. 搭建示例工程</h2><h3 id="3-1-1-创建工程"><a href="#3-1-1-创建工程" class="headerlink" title="3.1.1. 创建工程"></a>3.1.1. 创建工程</h3><p><img src="/myl-mm/assets/1558319510387.png" alt="1555991321159"></p>
<p><img src="/myl-mm/assets/1558319546688.png" alt="1555991353704"></p>
<h3 id="3-1-2-添加依赖"><a href="#3-1-2-添加依赖" class="headerlink" title="3.1.2. 添加依赖"></a>3.1.2. 添加依赖</h3><p>往heima-rabbitmq的pom.xml文件中添加如下依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.rabbitmq<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>amqp-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.6.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h2 id="3-2-编写生产者"><a href="#3-2-编写生产者" class="headerlink" title="3.2. 编写生产者"></a>3.2. 编写生产者</h2><p>编写消息生产者com.itheima.rabbitmq.simple.Producer</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.simple;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;simple_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">//创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">connectionFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//主机地址;默认为 localhost</span></span><br><span class="line">        connectionFactory.setHost(<span class="string">&quot;localhost&quot;</span>);</span><br><span class="line">        <span class="comment">//连接端口;默认为 5672</span></span><br><span class="line">        connectionFactory.setPort(<span class="number">5672</span>);</span><br><span class="line">        <span class="comment">//虚拟主机名称;默认为 /</span></span><br><span class="line">        connectionFactory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);</span><br><span class="line">        <span class="comment">//连接用户名；默认为guest</span></span><br><span class="line">        connectionFactory.setUsername(<span class="string">&quot;heima&quot;</span>);</span><br><span class="line">        <span class="comment">//连接密码；默认为guest</span></span><br><span class="line">        connectionFactory.setPassword(<span class="string">&quot;heima&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> connectionFactory.newConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 要发送的信息</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;你好；小兔子！&quot;</span>;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称，如果没有指定则使用默认Default Exchage</span></span><br><span class="line"><span class="comment">         * 参数2：路由key,简单模式可以传递队列名称</span></span><br><span class="line"><span class="comment">         * 参数3：消息其它属性</span></span><br><span class="line"><span class="comment">         * 参数4：消息内容</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>在执行上述的消息发送之后；可以登录rabbitMQ的管理控制台，可以发现队列和其消息：</p>
<p><img src="/myl-mm/assets/1556006638979.png" alt="1556006638979"></p>
<p><img src="/myl-mm/assets/1556006647177.png" alt="1556006647177"></p>
<h2 id="3-3-编写消费者"><a href="#3-3-编写消费者" class="headerlink" title="3.3. 编写消费者"></a>3.3. 编写消费者</h2><p>抽取创建connection的工具类com.itheima.rabbitmq.util.ConnectionUtil；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.util;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConnectionUtil</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title function_">getConnection</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">//创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">connectionFactory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//主机地址;默认为 localhost</span></span><br><span class="line">        connectionFactory.setHost(<span class="string">&quot;localhost&quot;</span>);</span><br><span class="line">        <span class="comment">//连接端口;默认为 5672</span></span><br><span class="line">        connectionFactory.setPort(<span class="number">5672</span>);</span><br><span class="line">        <span class="comment">//虚拟主机名称;默认为 /</span></span><br><span class="line">        connectionFactory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);</span><br><span class="line">        <span class="comment">//连接用户名；默认为guest</span></span><br><span class="line">        connectionFactory.setUsername(<span class="string">&quot;heima&quot;</span>);</span><br><span class="line">        <span class="comment">//连接密码；默认为guest</span></span><br><span class="line">        connectionFactory.setPassword(<span class="string">&quot;heima&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="keyword">return</span> connectionFactory.newConnection();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>编写消息的消费者com.itheima.rabbitmq.simple.Consumer</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.simple;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.QUEUE_NAME, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.QUEUE_NAME, <span class="literal">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//不关闭资源，应该一直监听消息</span></span><br><span class="line">        <span class="comment">//channel.close();</span></span><br><span class="line">        <span class="comment">//connection.close();</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-4-小结"><a href="#3-4-小结" class="headerlink" title="3.4. 小结"></a>3.4. 小结</h2><p>上述的入门案例中中其实使用的是如下的简单模式：</p>
<p><img src="/myl-mm/assets/1555991074575.png" alt="1555991074575"></p>
<p>在上图的模型中，有以下概念：</p>
<ul>
<li>P：生产者，也就是要发送消息的程序</li>
<li>C：消费者：消息的接受者，会一直等待消息到来。</li>
<li>queue：消息队列，图中红色部分。类似一个邮箱，可以缓存消息；生产者向其中投递消息，消费者从其中取出消息。</li>
</ul>
<h1 id="4-AMQP"><a href="#4-AMQP" class="headerlink" title="4. AMQP"></a>4. AMQP</h1><h2 id="4-1-相关概念介绍"><a href="#4-1-相关概念介绍" class="headerlink" title="4.1. 相关概念介绍"></a>4.1. 相关概念介绍</h2><p>AMQP  一个提供统一消息服务的应用层标准高级消息队列协议，是应用层协议的一个开放标准，为面向消息的中间件设计。</p>
<p>AMQP是一个二进制协议，拥有一些现代化特点：多信道、协商式，异步，安全，扩平台，中立，高效。</p>
<p>RabbitMQ是AMQP协议的Erlang的实现。</p>
<table>
<thead>
<tr>
<th>概念</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>连接Connection</td>
<td>一个网络连接，比如TCP&#x2F;IP套接字连接。</td>
</tr>
<tr>
<td>会话Session</td>
<td>端点之间的命名对话。在一个会话上下文中，保证“恰好传递一次”。</td>
</tr>
<tr>
<td>信道Channel</td>
<td>多路复用连接中的一条独立的双向数据流通道。为会话提供物理传输介质。</td>
</tr>
<tr>
<td>客户端Client</td>
<td>AMQP连接或者会话的发起者。AMQP是非对称的，客户端生产和消费消息，服务器存储和路由这些消息。</td>
</tr>
<tr>
<td>服务节点Broker</td>
<td>消息中间件的服务节点；一般情况下可以将一个RabbitMQ Broker看作一台RabbitMQ 服务器。</td>
</tr>
<tr>
<td>端点</td>
<td>AMQP对话的任意一方。一个AMQP连接包括两个端点（一个是客户端，一个是服务器）。</td>
</tr>
<tr>
<td>消费者Consumer</td>
<td>一个从消息队列里请求消息的客户端程序。</td>
</tr>
<tr>
<td>生产者Producer</td>
<td>一个向交换机发布消息的客户端应用程序。</td>
</tr>
</tbody></table>
<h2 id="4-2-RabbitMQ运转流程"><a href="#4-2-RabbitMQ运转流程" class="headerlink" title="4.2. RabbitMQ运转流程"></a>4.2. RabbitMQ运转流程</h2><p>在入门案例中：</p>
<ul>
<li>生产者发送消息<ol>
<li>生产者创建连接（Connection），开启一个信道（Channel），连接到RabbitMQ Broker；</li>
<li>声明队列并设置属性；如是否排它，是否持久化，是否自动删除；</li>
<li>将路由键（空字符串）与队列绑定起来；</li>
<li>发送消息至RabbitMQ Broker；</li>
<li>关闭信道；</li>
<li>关闭连接；</li>
</ol>
</li>
<li>消费者接收消息<ol>
<li>消费者创建连接（Connection），开启一个信道（Channel），连接到RabbitMQ Broker</li>
<li>向Broker 请求消费相应队列中的消息，设置相应的回调函数；</li>
<li>等待Broker回应闭关投递响应队列中的消息，消费者接收消息；</li>
<li>确认（ack，自动确认）接收到的消息；</li>
<li>RabbitMQ从队列中删除相应已经被确认的消息；</li>
<li>关闭信道；</li>
<li>关闭连接；</li>
</ol>
</li>
</ul>
<p><img src="/myl-mm/assets/1565105223969.png" alt="1565105223969"></p>
<h2 id="4-3-生产者流转过程说明"><a href="#4-3-生产者流转过程说明" class="headerlink" title="4.3. 生产者流转过程说明"></a>4.3. 生产者流转过程说明</h2><ol>
<li>客户端与代理服务器Broker建立连接。会调用newConnection() 方法,这个方法会进一步封装Protocol Header 0-9-1 的报文头发送给Broker ，以此通知Broker 本次交互采用的是AMQPO-9-1 协议，紧接着Broker 返回Connection.Start 来建立连接，在连接的过程中涉及Connection.Start&#x2F;.Start-OK 、Connection.Tune&#x2F;.Tune-Ok ，Connection.Open&#x2F; .Open-Ok 这6 个命令的交互。</li>
<li>客户端调用connection.createChannel方法。此方法开启信道，其包装的channel.open命令发送给Broker,等待channel.basicPublish方法，对应的AMQP命令为Basic.Publish,这个命令包含了content Header 和content Body()。content Header 包含了消息体的属性，例如:投递模式，优先级等，content Body 包含了消息体本身。</li>
<li>客户端发送完消息需要关闭资源时，涉及到Channel.Close和Channl.Close-Ok 与Connetion.Close和Connection.Close-Ok的命令交互。</li>
</ol>
<p><img src="/myl-mm/assets/%E7%94%9F%E4%BA%A7%E8%80%85%E6%B5%81%E8%BD%AC%E8%BF%87%E7%A8%8B%E5%9B%BE.bmp" alt="生产者流转过程图"></p>
<h2 id="4-4-消费者流转过程说明"><a href="#4-4-消费者流转过程说明" class="headerlink" title="4.4. 消费者流转过程说明"></a>4.4. 消费者流转过程说明</h2><ol>
<li>消费者客户端与代理服务器Broker建立连接。会调用newConnection() 方法,这个方法会进一步封装Protocol Header 0-9-1 的报文头发送给Broker ，以此通知Broker 本次交互采用的是AMQPO-9-1 协议，紧接着Broker 返回Connection.Start 来建立连接，在连接的过程中涉及Connection.Start&#x2F;.Start-OK 、Connection.Tune&#x2F;.Tune-Ok ，Connection.Open&#x2F; .Open-Ok 这6 个命令的交互。</li>
<li>消费者客户端调用connection.createChannel方法。和生产者客户端一样，协议涉及Channel . Open&#x2F;Open-Ok命令。</li>
<li>在真正消费之前，消费者客户端需要向Broker 发送Basic.Consume 命令(即调用channel.basicConsume 方法〉将Channel 置为接收模式，之后Broker 回执Basic . Consume - Ok 以告诉消费者客户端准备好消费消息。</li>
<li>Broker 向消费者客户端推送(Push) 消息，即Basic.Deliver 命令，这个命令和Basic.Publish 命令一样会携带Content Header 和Content Body。</li>
<li>消费者接收到消息并正确消费之后，向Broker 发送确认，即Basic.Ack 命令。</li>
<li>客户端发送完消息需要关闭资源时，涉及到Channel.Close和Channl.Close-Ok 与Connetion.Close和Connection.Close-Ok的命令交互。</li>
</ol>
<p><img src="/myl-mm/assets/%E6%B6%88%E8%B4%B9%E8%80%85%E6%B5%81%E8%BD%AC%E8%BF%87%E7%A8%8B%E5%9B%BE.bmp" alt="消费者流转过程图"></p>
<h1 id="5-RabbitMQ工作模式"><a href="#5-RabbitMQ工作模式" class="headerlink" title="5. RabbitMQ工作模式"></a>5. RabbitMQ工作模式</h1><h2 id="4-1-Work-queues工作队列模式"><a href="#4-1-Work-queues工作队列模式" class="headerlink" title="4.1. Work queues工作队列模式"></a>4.1. Work queues工作队列模式</h2><h3 id="4-1-1-模式说明"><a href="#4-1-1-模式说明" class="headerlink" title="4.1.1. 模式说明"></a>4.1.1. 模式说明</h3><p><img src="/myl-mm/assets/1556009144848.png" alt="1556009144848"></p>
<p><code>Work Queues</code>与入门程序的<code>简单模式</code>相比，多了一个或一些消费端，多个消费端共同消费同一个队列中的消息。</p>
<p><strong>应用场景</strong>：对于 任务过重或任务较多情况使用工作队列可以提高任务处理的速度。</p>
<h3 id="4-1-2-代码"><a href="#4-1-2-代码" class="headerlink" title="4.1.2. 代码"></a>4.1.2. 代码</h3><p><code>Work Queues</code>与入门程序的<code>简单模式</code>的代码是几乎一样的；可以完全复制，并复制多一个消费者进行多个消费者同时消费消息的测试。</p>
<h4 id="1）生产者"><a href="#1）生产者" class="headerlink" title="1）生产者"></a>1）生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.work;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">QUEUE_NAME</span> <span class="operator">=</span> <span class="string">&quot;work_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;= <span class="number">30</span>; i++) &#123;</span><br><span class="line">            <span class="comment">// 发送信息</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;你好；小兔子！work模式--&quot;</span> + i;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 参数1：交换机名称，如果没有指定则使用默认Default Exchage</span></span><br><span class="line"><span class="comment">             * 参数2：路由key,简单模式可以传递队列名称</span></span><br><span class="line"><span class="comment">             * 参数3：消息其它属性</span></span><br><span class="line"><span class="comment">             * 参数4：消息内容</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">            System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="2）消费者1"><a href="#2）消费者1" class="headerlink" title="2）消费者1"></a>2）消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.work;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.QUEUE_NAME, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//一次只能接收并处理一个消息</span></span><br><span class="line">        channel.basicQos(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">//路由key</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                    <span class="comment">//交换机</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                    <span class="comment">//消息id</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                    <span class="comment">//收到的消息</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;消费者1-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">                    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//确认消息</span></span><br><span class="line">                    channel.basicAck(envelope.getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.QUEUE_NAME, <span class="literal">false</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3）消费者2"><a href="#3）消费者2" class="headerlink" title="3）消费者2"></a>3）消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.work;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer2</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.QUEUE_NAME, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//一次只能接收并处理一个消息</span></span><br><span class="line">        channel.basicQos(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">//路由key</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                    <span class="comment">//交换机</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                    <span class="comment">//消息id</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                    <span class="comment">//收到的消息</span></span><br><span class="line">                    System.out.println(<span class="string">&quot;消费者2-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">                    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//确认消息</span></span><br><span class="line">                    channel.basicAck(envelope.getDeliveryTag(), <span class="literal">false</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.QUEUE_NAME, <span class="literal">false</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="4-1-3-测试"><a href="#4-1-3-测试" class="headerlink" title="4.1.3. 测试"></a>4.1.3. 测试</h3><p>启动两个消费者，然后再启动生产者发送消息；到IDEA的两个消费者对应的控制台查看是否竞争性的接收到消息。</p>
<p><img src="/myl-mm/assets/1556014310859.png" alt="1556014310859"></p>
<p><img src="/myl-mm/assets/1556014318106.png" alt="1556014318106"></p>
<h3 id="4-1-4-小结"><a href="#4-1-4-小结" class="headerlink" title="4.1.4. 小结"></a>4.1.4. 小结</h3><p>在一个队列中如果有多个消费者，那么消费者之间对于同一个消息的关系是<strong>竞争</strong>的关系。</p>
<h2 id="4-2-订阅模式类型"><a href="#4-2-订阅模式类型" class="headerlink" title="4.2. 订阅模式类型"></a>4.2. 订阅模式类型</h2><p>订阅模式示例图：</p>
<p><img src="/myl-mm/assets/1556014499573.png" alt="1556014499573"></p>
<p>前面2个案例中，只有3个角色：</p>
<ul>
<li>P：生产者，也就是要发送消息的程序</li>
<li>C：消费者：消息的接受者，会一直等待消息到来。</li>
<li>queue：消息队列，图中红色部分</li>
</ul>
<p>而在订阅模型中，多了一个exchange角色，而且过程略有变化：</p>
<ul>
<li>P：生产者，也就是要发送消息的程序，但是不再发送到队列中，而是发给X（交换机）</li>
<li>C：消费者，消息的接受者，会一直等待消息到来。</li>
<li>Queue：消息队列，接收消息、缓存消息。</li>
<li>Exchange：交换机，图中的X。一方面，接收生产者发送的消息。另一方面，知道如何处理消息，例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作，取决于Exchange的类型。Exchange有常见以下3种类型：<ul>
<li>Fanout：广播，将消息交给所有绑定到交换机的队列</li>
<li>Direct：定向，把消息交给符合指定routing key 的队列</li>
<li>Topic：通配符，把消息交给符合routing pattern（路由模式） 的队列</li>
</ul>
</li>
</ul>
<p><strong>Exchange（交换机）只负责转发消息，不具备存储消息的能力</strong>，因此如果没有任何队列与Exchange绑定，或者没有符合路由规则的队列，那么消息会丢失！</p>
<h2 id="4-3-Publish-x2F-Subscribe发布与订阅模式"><a href="#4-3-Publish-x2F-Subscribe发布与订阅模式" class="headerlink" title="4.3. Publish&#x2F;Subscribe发布与订阅模式"></a>4.3. Publish&#x2F;Subscribe发布与订阅模式</h2><h3 id="4-3-1-模式说明"><a href="#4-3-1-模式说明" class="headerlink" title="4.3.1. 模式说明"></a>4.3.1. 模式说明</h3><p><img src="/myl-mm/assets/1556010329032.png" alt="1556010329032"></p>
<p>发布订阅模式：<br>1、每个消费者监听自己的队列。<br>2、生产者将消息发给broker，由交换机将消息转发到绑定此交换机的每个队列，每个绑定交换机的队列都将接收<br>到消息</p>
<h3 id="4-3-2-代码"><a href="#4-3-2-代码" class="headerlink" title="4.3.2. 代码"></a>4.3.2. 代码</h3><h4 id="1）生产者-1"><a href="#1）生产者-1" class="headerlink" title="1）生产者"></a>1）生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.ps;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发布与订阅使用的交换机类型为：fanout</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">FANOUT_EXCHAGE</span> <span class="operator">=</span> <span class="string">&quot;fanout_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">FANOUT_QUEUE_1</span> <span class="operator">=</span> <span class="string">&quot;fanout_queue_1&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">FANOUT_QUEUE_2</span> <span class="operator">=</span> <span class="string">&quot;fanout_queue_2&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 声明交换机</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称</span></span><br><span class="line"><span class="comment">         * 参数2：交换机类型，fanout、topic、direct、headers</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.exchangeDeclare(FANOUT_EXCHAGE, BuiltinExchangeType.FANOUT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(FANOUT_QUEUE_1, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        channel.queueDeclare(FANOUT_QUEUE_2, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(FANOUT_QUEUE_1, FANOUT_EXCHAGE, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        channel.queueBind(FANOUT_QUEUE_2, FANOUT_EXCHAGE, <span class="string">&quot;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;= <span class="number">10</span>; i++) &#123;</span><br><span class="line">            <span class="comment">// 发送信息</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;你好；小兔子！发布订阅模式--&quot;</span> + i;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 参数1：交换机名称，如果没有指定则使用默认Default Exchage</span></span><br><span class="line"><span class="comment">             * 参数2：路由key,简单模式可以传递队列名称</span></span><br><span class="line"><span class="comment">             * 参数3：消息其它属性</span></span><br><span class="line"><span class="comment">             * 参数4：消息内容</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            channel.basicPublish(FANOUT_EXCHAGE, <span class="string">&quot;&quot;</span>, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">            System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="2）消费者1-1"><a href="#2）消费者1-1" class="headerlink" title="2）消费者1"></a>2）消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.ps;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(Producer.FANOUT_EXCHAGE, BuiltinExchangeType.FANOUT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.FANOUT_QUEUE_1, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(Producer.FANOUT_QUEUE_1, Producer.FANOUT_EXCHAGE, <span class="string">&quot;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消费者1-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.FANOUT_QUEUE_1, <span class="literal">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="3）消费者2-1"><a href="#3）消费者2-1" class="headerlink" title="3）消费者2"></a>3）消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.ps;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer2</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(Producer.FANOUT_EXCHAGE, BuiltinExchangeType.FANOUT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.FANOUT_QUEUE_2, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(Producer.FANOUT_QUEUE_2, Producer.FANOUT_EXCHAGE, <span class="string">&quot;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消费者2-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.FANOUT_QUEUE_2, <span class="literal">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="4-3-3-测试"><a href="#4-3-3-测试" class="headerlink" title="4.3.3. 测试"></a>4.3.3. 测试</h3><p>启动所有消费者，然后使用生产者发送消息；在每个消费者对应的控制台可以查看到生产者发送的所有消息；到达<strong>广播</strong>的效果。</p>
<p>在执行完测试代码后，其实到RabbitMQ的管理后台找到<code>Exchanges</code>选项卡，点击 <code>fanout_exchange</code> 的交换机，可以查看到如下的绑定：</p>
<p><img src="/myl-mm/assets/1556015006220.png" alt="1556015006220"></p>
<h3 id="4-3-4-小结"><a href="#4-3-4-小结" class="headerlink" title="4.3.4. 小结"></a>4.3.4. 小结</h3><p>交换机需要与队列进行绑定，绑定之后；一个消息可以被多个消费者都收到。</p>
<p><strong>发布订阅模式与工作队列模式的区别</strong></p>
<p>1、工作队列模式不用定义交换机，而发布&#x2F;订阅模式需要定义交换机。 </p>
<p>2、发布&#x2F;订阅模式的生产方是面向交换机发送消息，工作队列模式的生产方是面向队列发送消息(底层使用默认交换机)。</p>
<p>3、发布&#x2F;订阅模式需要设置队列和交换机的绑定，工作队列模式不需要设置，实际上工作队列模式会将队列绑 定到默认的交换机 。</p>
<h2 id="4-4-Routing路由模式"><a href="#4-4-Routing路由模式" class="headerlink" title="4.4. Routing路由模式"></a>4.4. Routing路由模式</h2><h3 id="4-4-1-模式说明"><a href="#4-4-1-模式说明" class="headerlink" title="4.4.1. 模式说明"></a>4.4.1. 模式说明</h3><p>路由模式特点：</p>
<ul>
<li>队列与交换机的绑定，不能是任意绑定了，而是要指定一个<code>RoutingKey</code>（路由key）</li>
<li>消息的发送方在 向 Exchange发送消息时，也必须指定消息的 <code>RoutingKey</code>。</li>
<li>Exchange不再把消息交给每一个绑定的队列，而是根据消息的<code>Routing Key</code>进行判断，只有队列的<code>Routingkey</code>与消息的 <code>Routing key</code>完全一致，才会接收到消息</li>
</ul>
<p><img src="/myl-mm/assets/1556029284397.png" alt="1556029284397"></p>
<p>图解：</p>
<ul>
<li>P：生产者，向Exchange发送消息，发送消息时，会指定一个routing key。</li>
<li>X：Exchange（交换机），接收生产者的消息，然后把消息递交给 与routing key完全匹配的队列</li>
<li>C1：消费者，其所在队列指定了需要routing key 为 error 的消息</li>
<li>C2：消费者，其所在队列指定了需要routing key 为 info、error、warning 的消息</li>
</ul>
<h3 id="4-4-2-代码"><a href="#4-4-2-代码" class="headerlink" title="4.4.2. 代码"></a>4.4.2. 代码</h3><p>在编码上与 <code>Publish/Subscribe发布与订阅模式</code> 的区别是交换机的类型为：Direct，还有队列绑定交换机的时候需要指定routing key。</p>
<h4 id="1）生产者-2"><a href="#1）生产者-2" class="headerlink" title="1）生产者"></a>1）生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.routing;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 路由模式的交换机类型为：direct</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DIRECT_EXCHAGE</span> <span class="operator">=</span> <span class="string">&quot;direct_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DIRECT_QUEUE_INSERT</span> <span class="operator">=</span> <span class="string">&quot;direct_queue_insert&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">DIRECT_QUEUE_UPDATE</span> <span class="operator">=</span> <span class="string">&quot;direct_queue_update&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 声明交换机</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称</span></span><br><span class="line"><span class="comment">         * 参数2：交换机类型，fanout、topic、direct、headers</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.exchangeDeclare(DIRECT_EXCHAGE, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(DIRECT_QUEUE_INSERT, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        channel.queueDeclare(DIRECT_QUEUE_UPDATE, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(DIRECT_QUEUE_INSERT, DIRECT_EXCHAGE, <span class="string">&quot;insert&quot;</span>);</span><br><span class="line">        channel.queueBind(DIRECT_QUEUE_UPDATE, DIRECT_EXCHAGE, <span class="string">&quot;update&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 发送信息</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;新增了商品。路由模式；routing key 为 insert &quot;</span> ;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称，如果没有指定则使用默认Default Exchage</span></span><br><span class="line"><span class="comment">         * 参数2：路由key,简单模式可以传递队列名称</span></span><br><span class="line"><span class="comment">         * 参数3：消息其它属性</span></span><br><span class="line"><span class="comment">         * 参数4：消息内容</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicPublish(DIRECT_EXCHAGE, <span class="string">&quot;insert&quot;</span>, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 发送信息</span></span><br><span class="line">        message = <span class="string">&quot;修改了商品。路由模式；routing key 为 update&quot;</span> ;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称，如果没有指定则使用默认Default Exchage</span></span><br><span class="line"><span class="comment">         * 参数2：路由key,简单模式可以传递队列名称</span></span><br><span class="line"><span class="comment">         * 参数3：消息其它属性</span></span><br><span class="line"><span class="comment">         * 参数4：消息内容</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicPublish(DIRECT_EXCHAGE, <span class="string">&quot;update&quot;</span>, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="2）消费者1-2"><a href="#2）消费者1-2" class="headerlink" title="2）消费者1"></a>2）消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.routing;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(Producer.DIRECT_EXCHAGE, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.DIRECT_QUEUE_INSERT, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(Producer.DIRECT_QUEUE_INSERT, Producer.DIRECT_EXCHAGE, <span class="string">&quot;insert&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消费者1-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.DIRECT_QUEUE_INSERT, <span class="literal">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="3）消费者2-2"><a href="#3）消费者2-2" class="headerlink" title="3）消费者2"></a>3）消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.routing;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer2</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(Producer.DIRECT_EXCHAGE, BuiltinExchangeType.DIRECT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.DIRECT_QUEUE_UPDATE, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(Producer.DIRECT_QUEUE_UPDATE, Producer.DIRECT_EXCHAGE, <span class="string">&quot;update&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消费者2-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.DIRECT_QUEUE_UPDATE, <span class="literal">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<h3 id="4-4-3-测试"><a href="#4-4-3-测试" class="headerlink" title="4.4.3. 测试"></a>4.4.3. 测试</h3><p>启动所有消费者，然后使用生产者发送消息；在消费者对应的控制台可以查看到生产者发送对应routing key对应队列的消息；到达<strong>按照需要接收</strong>的效果。</p>
<p>在执行完测试代码后，其实到RabbitMQ的管理后台找到<code>Exchanges</code>选项卡，点击 <code>direct_exchange</code> 的交换机，可以查看到如下的绑定：</p>
<p><img src="/myl-mm/assets/1556031175744.png" alt="1556031175744"></p>
<h3 id="4-4-4-小结"><a href="#4-4-4-小结" class="headerlink" title="4.4.4. 小结"></a>4.4.4. 小结</h3><p>Routing模式要求队列在绑定交换机时要指定routing key，消息会转发到符合routing key的队列。</p>
<h2 id="4-5-Topics通配符模式"><a href="#4-5-Topics通配符模式" class="headerlink" title="4.5. Topics通配符模式"></a>4.5. Topics通配符模式</h2><h3 id="4-5-1-模式说明"><a href="#4-5-1-模式说明" class="headerlink" title="4.5.1. 模式说明"></a>4.5.1. 模式说明</h3><p><code>Topic</code>类型与<code>Direct</code>相比，都是可以根据<code>RoutingKey</code>把消息路由到不同的队列。只不过<code>Topic</code>类型<code>Exchange</code>可以让队列在绑定<code>Routing key</code> 的时候<strong>使用通配符</strong>！</p>
<p><code>Routingkey</code> 一般都是有一个或多个单词组成，多个单词之间以”.”分割，例如： <code>item.insert</code></p>
<p> 通配符规则：</p>
<p><code>#</code>：匹配一个或多个词</p>
<p><code>*</code>：匹配不多不少恰好1个词</p>
<p>举例：</p>
<p><code>item.#</code>：能够匹配<code>item.insert.abc</code> 或者 <code>item.insert</code></p>
<p><code>item.*</code>：只能匹配<code>item.insert</code></p>
<p><img src="/myl-mm/assets/1556031362048.png" alt="1556031362048"></p>
<p><img src="/myl-mm/assets/1556031519931.png" alt="1556031519931"></p>
<p>图解：</p>
<ul>
<li>红色Queue：绑定的是<code>usa.#</code> ，因此凡是以 <code>usa.</code>开头的<code>routing key</code> 都会被匹配到</li>
<li>黄色Queue：绑定的是<code>#.news</code> ，因此凡是以 <code>.news</code>结尾的 <code>routing key</code> 都会被匹配</li>
</ul>
<h3 id="4-5-2-代码"><a href="#4-5-2-代码" class="headerlink" title="4.5.2. 代码"></a>4.5.2. 代码</h3><h4 id="1）生产者-3"><a href="#1）生产者-3" class="headerlink" title="1）生产者"></a>1）生产者</h4><p>使用topic类型的Exchange，发送消息的routing key有3种： <code>item.insert</code>、<code>item.update</code>、<code>item.delete</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.topic;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 通配符Topic的交换机类型为：topic</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TOPIC_EXCHAGE</span> <span class="operator">=</span> <span class="string">&quot;topic_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TOPIC_QUEUE_1</span> <span class="operator">=</span> <span class="string">&quot;topic_queue_1&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">TOPIC_QUEUE_2</span> <span class="operator">=</span> <span class="string">&quot;topic_queue_2&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建连接</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 声明交换机</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称</span></span><br><span class="line"><span class="comment">         * 参数2：交换机类型，fanout、topic、topic、headers</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.exchangeDeclare(TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 发送信息</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;新增了商品。Topic模式；routing key 为 item.insert &quot;</span> ;</span><br><span class="line">        channel.basicPublish(TOPIC_EXCHAGE, <span class="string">&quot;item.insert&quot;</span>, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 发送信息</span></span><br><span class="line">        message = <span class="string">&quot;修改了商品。Topic模式；routing key 为 item.update&quot;</span> ;</span><br><span class="line">        channel.basicPublish(TOPIC_EXCHAGE, <span class="string">&quot;item.update&quot;</span>, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 发送信息</span></span><br><span class="line">        message = <span class="string">&quot;删除了商品。Topic模式；routing key 为 item.delete&quot;</span> ;</span><br><span class="line">        channel.basicPublish(TOPIC_EXCHAGE, <span class="string">&quot;item.delete&quot;</span>, <span class="literal">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot;已发送消息：&quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="2）消费者1-3"><a href="#2）消费者1-3" class="headerlink" title="2）消费者1"></a>2）消费者1</h4><p>接收两种类型的消息：更新商品和删除商品</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.topic;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(Producer.TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.TOPIC_QUEUE_1, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(Producer.TOPIC_QUEUE_1, Producer.TOPIC_EXCHAGE, <span class="string">&quot;item.update&quot;</span>);</span><br><span class="line">        channel.queueBind(Producer.TOPIC_QUEUE_1, Producer.TOPIC_EXCHAGE, <span class="string">&quot;item.delete&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消费者1-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.TOPIC_QUEUE_1, <span class="literal">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="3）消费者2-3"><a href="#3）消费者2-3" class="headerlink" title="3）消费者2"></a>3）消费者2</h4><p>接收所有类型的消息：新增商品，更新商品和删除商品。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.topic;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.util.ConnectionUtil;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer2</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> ConnectionUtil.getConnection();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建频道</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//声明交换机</span></span><br><span class="line">        channel.exchangeDeclare(Producer.TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否定义持久化队列</span></span><br><span class="line"><span class="comment">         * 参数3：是否独占本次连接</span></span><br><span class="line"><span class="comment">         * 参数4：是否在不使用的时候自动删除队列</span></span><br><span class="line"><span class="comment">         * 参数5：队列其它参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueDeclare(Producer.TOPIC_QUEUE_2, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//队列绑定交换机</span></span><br><span class="line">        channel.queueBind(Producer.TOPIC_QUEUE_2, Producer.TOPIC_EXCHAGE, <span class="string">&quot;item.*&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建消费者；并设置消息处理</span></span><br><span class="line">        <span class="type">DefaultConsumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * consumerTag 消息者标签，在channel.basicConsume时候可以指定</span></span><br><span class="line"><span class="comment">             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">             * properties 属性信息</span></span><br><span class="line"><span class="comment">             * body 消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                System.out.println(<span class="string">&quot;路由key为：&quot;</span> + envelope.getRoutingKey());</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                System.out.println(<span class="string">&quot;交换机为：&quot;</span> + envelope.getExchange());</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消息id为：&quot;</span> + envelope.getDeliveryTag());</span><br><span class="line">                <span class="comment">//收到的消息</span></span><br><span class="line">                System.out.println(<span class="string">&quot;消费者2-接收到的消息为：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body, <span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">//监听消息</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：队列名称</span></span><br><span class="line"><span class="comment">         * 参数2：是否自动确认，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动确认</span></span><br><span class="line"><span class="comment">         * 参数3：消息接收到后回调</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.basicConsume(Producer.TOPIC_QUEUE_2, <span class="literal">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-5-3-测试"><a href="#4-5-3-测试" class="headerlink" title="4.5.3. 测试"></a>4.5.3. 测试</h3><p>启动所有消费者，然后使用生产者发送消息；在消费者对应的控制台可以查看到生产者发送对应routing key对应队列的消息；到达<strong>按照需要接收</strong>的效果；并且这些routing key可以使用通配符。</p>
<p>在执行完测试代码后，其实到RabbitMQ的管理后台找到<code>Exchanges</code>选项卡，点击 <code>topic_exchange</code> 的交换机，可以查看到如下的绑定：</p>
<p><img src="/myl-mm/assets/1556032433333.png" alt="1556032433333"></p>
<h3 id="4-5-4-小结"><a href="#4-5-4-小结" class="headerlink" title="4.5.4. 小结"></a>4.5.4. 小结</h3><p>Topic主题模式可以实现 <code>Publish/Subscribe发布与订阅模式</code> 和 <code> Routing路由模式</code> 的功能；只是Topic在配置routing key 的时候可以使用通配符，显得更加灵活。</p>
<h2 id="4-6-模式总结"><a href="#4-6-模式总结" class="headerlink" title="4.6. 模式总结"></a>4.6. 模式总结</h2><p>RabbitMQ工作模式：<br><strong>1、简单模式 HelloWorld</strong><br>一个生产者、一个消费者，不需要设置交换机（使用默认的交换机）</p>
<p><strong>2、工作队列模式 Work Queue</strong><br>一个生产者、多个消费者（竞争关系），不需要设置交换机（使用默认的交换机）</p>
<p><strong>3、发布订阅模式 Publish&#x2F;subscribe</strong><br>需要设置类型为fanout的交换机，并且交换机和队列进行绑定，当发送消息到交换机后，交换机会将消息发送到绑定的队列</p>
<p><strong>4、路由模式 Routing</strong><br>需要设置类型为direct的交换机，交换机和队列进行绑定，并且指定routing key，当发送消息到交换机后，交换机会根据routing key将消息发送到对应的队列</p>
<p><strong>5、通配符模式 Topic</strong><br>需要设置类型为topic的交换机，交换机和队列进行绑定，并且指定通配符方式的routing key，当发送消息到交换机后，交换机会根据routing key将消息发送到对应的队列</p>
<h1 id="5-Spring-整合RabbitMQ"><a href="#5-Spring-整合RabbitMQ" class="headerlink" title="5. Spring 整合RabbitMQ"></a>5. Spring 整合RabbitMQ</h1><h2 id="5-1-搭建生产者工程"><a href="#5-1-搭建生产者工程" class="headerlink" title="5.1. 搭建生产者工程"></a>5.1. 搭建生产者工程</h2><h3 id="5-1-1-创建工程"><a href="#5-1-1-创建工程" class="headerlink" title="5.1.1. 创建工程"></a>5.1.1. 创建工程</h3><p><img src="/myl-mm/assets/1565149342994.png" alt="1565149342994"></p>
<p><img src="/myl-mm/assets/1565144326498.png" alt="1565144326498"></p>
<h3 id="5-1-2-添加依赖"><a href="#5-1-2-添加依赖" class="headerlink" title="5.1.2. 添加依赖"></a>5.1.2. 添加依赖</h3><p>修改pom.xml文件内容为如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.itheima<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-rabbitmq-producer<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-context<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.amqp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-rabbit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.8.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="5-1-3-配置整合"><a href="#5-1-3-配置整合" class="headerlink" title="5.1.3. 配置整合"></a>5.1.3. 配置整合</h3><ol>
<li>创建<code>spring-rabbitmq-producer\src\main\resources\properties\rabbitmq.properties</code>连接参数等配置文件；</li>
</ol>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">rabbitmq.host</span>=<span class="string">192.168.12.135</span></span><br><span class="line"><span class="attr">rabbitmq.port</span>=<span class="string">5672</span></span><br><span class="line"><span class="attr">rabbitmq.username</span>=<span class="string">heima</span></span><br><span class="line"><span class="attr">rabbitmq.password</span>=<span class="string">heima</span></span><br><span class="line"><span class="attr">rabbitmq.virtual-host</span>=<span class="string">/itcast</span></span><br></pre></td></tr></table></figure>



<ol start="2">
<li>创建 <code>spring-rabbitmq-producer\src\main\resources\spring\spring-rabbitmq.xml</code> 整合配置文件；</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:context</span>=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:rabbit</span>=<span class="string">&quot;http://www.springframework.org/schema/rabbit&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="string"><span class="tag">       https://www.springframework.org/schema/context/spring-context.xsd</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/rabbit</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--加载配置文件--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:property-placeholder</span> <span class="attr">location</span>=<span class="string">&quot;classpath:properties/rabbitmq.properties&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 定义rabbitmq connectionFactory --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:connection-factory</span> <span class="attr">id</span>=<span class="string">&quot;connectionFactory&quot;</span> <span class="attr">host</span>=<span class="string">&quot;$&#123;rabbitmq.host&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">port</span>=<span class="string">&quot;$&#123;rabbitmq.port&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">username</span>=<span class="string">&quot;$&#123;rabbitmq.username&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">password</span>=<span class="string">&quot;$&#123;rabbitmq.password&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">virtual-host</span>=<span class="string">&quot;$&#123;rabbitmq.virtual-host&#125;&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义管理交换机、队列--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:admin</span> <span class="attr">connection-factory</span>=<span class="string">&quot;connectionFactory&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义持久化队列，不存在则自动创建；不绑定到交换机则绑定到默认交换机</span></span><br><span class="line"><span class="comment">    默认交换机类型为direct，名字为：&quot;&quot;，路由键为队列的名称</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">&quot;spring_queue&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_queue&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播；所有队列都能收到消息~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义广播交换机中的持久化队列，不存在则自动创建--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">&quot;spring_fanout_queue_1&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_fanout_queue_1&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义广播交换机中的持久化队列，不存在则自动创建--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">&quot;spring_fanout_queue_2&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_fanout_queue_2&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义广播类型交换机；并绑定上述两个队列--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:fanout-exchange</span> <span class="attr">id</span>=<span class="string">&quot;spring_fanout_exchange&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_fanout_exchange&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:bindings</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">rabbit:binding</span> <span class="attr">queue</span>=<span class="string">&quot;spring_fanout_queue_1&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">rabbit:binding</span> <span class="attr">queue</span>=<span class="string">&quot;spring_fanout_queue_2&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">rabbit:bindings</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">rabbit:fanout-exchange</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符；*匹配一个单词，#匹配多个单词 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义广播交换机中的持久化队列，不存在则自动创建--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">&quot;spring_topic_queue_star&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_topic_queue_star&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义广播交换机中的持久化队列，不存在则自动创建--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">&quot;spring_topic_queue_well&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_topic_queue_well&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义广播交换机中的持久化队列，不存在则自动创建--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">&quot;spring_topic_queue_well2&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_topic_queue_well2&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:topic-exchange</span> <span class="attr">id</span>=<span class="string">&quot;spring_topic_exchange&quot;</span> <span class="attr">name</span>=<span class="string">&quot;spring_topic_exchange&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:bindings</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">rabbit:binding</span> <span class="attr">pattern</span>=<span class="string">&quot;heima.*&quot;</span> <span class="attr">queue</span>=<span class="string">&quot;spring_topic_queue_star&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">rabbit:binding</span> <span class="attr">pattern</span>=<span class="string">&quot;heima.#&quot;</span> <span class="attr">queue</span>=<span class="string">&quot;spring_topic_queue_well&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">rabbit:binding</span> <span class="attr">pattern</span>=<span class="string">&quot;itcast.#&quot;</span> <span class="attr">queue</span>=<span class="string">&quot;spring_topic_queue_well2&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">rabbit:bindings</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">rabbit:topic-exchange</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义rabbitTemplate对象操作可以在代码中方便发送消息--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:template</span> <span class="attr">id</span>=<span class="string">&quot;rabbitTemplate&quot;</span> <span class="attr">connection-factory</span>=<span class="string">&quot;connectionFactory&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="5-1-4-发送消息"><a href="#5-1-4-发送消息" class="headerlink" title="5.1.4. 发送消息"></a>5.1.4. 发送消息</h3><p>创建测试文件 <code>spring-rabbitmq-producer\src\test\java\com\itheima\rabbitmq\ProducerTest.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RunWith(SpringJUnit4ClassRunner.class)</span></span><br><span class="line"><span class="meta">@ContextConfiguration(locations = &quot;classpath:spring/spring-rabbitmq.xml&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 只发队列消息</span></span><br><span class="line"><span class="comment">     * 默认交换机类型为 direct</span></span><br><span class="line"><span class="comment">     * 交换机的名称为空，路由键为队列的名称</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">queueTest</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">//路由键与队列同名</span></span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;spring_queue&quot;</span>, <span class="string">&quot;只发队列spring_queue的消息。&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 发送广播</span></span><br><span class="line"><span class="comment">     * 交换机类型为 fanout</span></span><br><span class="line"><span class="comment">     * 绑定到该交换机的所有队列都能够收到消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fanoutTest</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称</span></span><br><span class="line"><span class="comment">         * 参数2：路由键名（广播设置为空）</span></span><br><span class="line"><span class="comment">         * 参数3：发送的消息内容</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;spring_fanout_exchange&quot;</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;发送到spring_fanout_exchange交换机的广播消息&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 通配符</span></span><br><span class="line"><span class="comment">     * 交换机类型为 topic</span></span><br><span class="line"><span class="comment">     * 匹配路由键的通配符，*表示一个单词，#表示多个单词</span></span><br><span class="line"><span class="comment">     * 绑定到该交换机的匹配队列能够收到对应消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">topicTest</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 参数1：交换机名称</span></span><br><span class="line"><span class="comment">         * 参数2：路由键名</span></span><br><span class="line"><span class="comment">         * 参数3：发送的消息内容</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;spring_topic_exchange&quot;</span>, <span class="string">&quot;heima.bj&quot;</span>, <span class="string">&quot;发送到spring_topic_exchange交换机heima.bj的消息&quot;</span>);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;spring_topic_exchange&quot;</span>, <span class="string">&quot;heima.bj.1&quot;</span>, <span class="string">&quot;发送到spring_topic_exchange交换机heima.bj.1的消息&quot;</span>);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;spring_topic_exchange&quot;</span>, <span class="string">&quot;heima.bj.2&quot;</span>, <span class="string">&quot;发送到spring_topic_exchange交换机heima.bj.2的消息&quot;</span>);</span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;spring_topic_exchange&quot;</span>, <span class="string">&quot;itcast.cn&quot;</span>, <span class="string">&quot;发送到spring_topic_exchange交换机itcast.cn的消息&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="5-2-搭建消费者工程"><a href="#5-2-搭建消费者工程" class="headerlink" title="5.2. 搭建消费者工程"></a>5.2. 搭建消费者工程</h2><h3 id="5-2-1-创建工程"><a href="#5-2-1-创建工程" class="headerlink" title="5.2.1. 创建工程"></a>5.2.1. 创建工程</h3><p><img src="/myl-mm/assets/1565149374831.png" alt="1565149374831"></p>
<p><img src="/myl-mm/assets/1565144775216.png" alt="1565144775216"></p>
<h3 id="5-2-2-添加依赖"><a href="#5-2-2-添加依赖" class="headerlink" title="5.2.2. 添加依赖"></a>5.2.2. 添加依赖</h3><p>修改pom.xml文件内容为如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.itheima<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-rabbitmq-consumer<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-context<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.7.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.amqp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-rabbit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.8.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="5-2-3-配置整合"><a href="#5-2-3-配置整合" class="headerlink" title="5.2.3. 配置整合"></a>5.2.3. 配置整合</h3><ol>
<li>创建<code>spring-rabbitmq-consumer\src\main\resources\properties\rabbitmq.properties</code>连接参数等配置文件；</li>
</ol>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">rabbitmq.host</span>=<span class="string">192.168.12.135</span></span><br><span class="line"><span class="attr">rabbitmq.port</span>=<span class="string">5672</span></span><br><span class="line"><span class="attr">rabbitmq.username</span>=<span class="string">heima</span></span><br><span class="line"><span class="attr">rabbitmq.password</span>=<span class="string">heima</span></span><br><span class="line"><span class="attr">rabbitmq.virtual-host</span>=<span class="string">/itcast</span></span><br></pre></td></tr></table></figure>



<ol start="2">
<li>创建 <code>spring-rabbitmq-consumer\src\main\resources\spring\spring-rabbitmq.xml</code> 整合配置文件；</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:context</span>=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:rabbit</span>=<span class="string">&quot;http://www.springframework.org/schema/rabbit&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="string"><span class="tag">       https://www.springframework.org/schema/context/spring-context.xsd</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/rabbit</span></span></span><br><span class="line"><span class="string"><span class="tag">       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--加载配置文件--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:property-placeholder</span> <span class="attr">location</span>=<span class="string">&quot;classpath:properties/rabbitmq.properties&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 定义rabbitmq connectionFactory --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:connection-factory</span> <span class="attr">id</span>=<span class="string">&quot;connectionFactory&quot;</span> <span class="attr">host</span>=<span class="string">&quot;$&#123;rabbitmq.host&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">port</span>=<span class="string">&quot;$&#123;rabbitmq.port&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">username</span>=<span class="string">&quot;$&#123;rabbitmq.username&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">password</span>=<span class="string">&quot;$&#123;rabbitmq.password&#125;&quot;</span></span></span><br><span class="line"><span class="tag">                               <span class="attr">virtual-host</span>=<span class="string">&quot;$&#123;rabbitmq.virtual-host&#125;&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;springQueueListener&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.rabbitmq.listener.SpringQueueListener&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;fanoutListener1&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.rabbitmq.listener.FanoutListener1&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;fanoutListener2&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.rabbitmq.listener.FanoutListener2&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;topicListenerStar&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.rabbitmq.listener.TopicListenerStar&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;topicListenerWell&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.rabbitmq.listener.TopicListenerWell&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;topicListenerWell2&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.itheima.rabbitmq.listener.TopicListenerWell2&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">rabbit:listener-container</span> <span class="attr">connection-factory</span>=<span class="string">&quot;connectionFactory&quot;</span> <span class="attr">auto-declare</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">ref</span>=<span class="string">&quot;springQueueListener&quot;</span> <span class="attr">queue-names</span>=<span class="string">&quot;spring_queue&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">ref</span>=<span class="string">&quot;fanoutListener1&quot;</span> <span class="attr">queue-names</span>=<span class="string">&quot;spring_fanout_queue_1&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">ref</span>=<span class="string">&quot;fanoutListener2&quot;</span> <span class="attr">queue-names</span>=<span class="string">&quot;spring_fanout_queue_2&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">ref</span>=<span class="string">&quot;topicListenerStar&quot;</span> <span class="attr">queue-names</span>=<span class="string">&quot;spring_topic_queue_star&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">ref</span>=<span class="string">&quot;topicListenerWell&quot;</span> <span class="attr">queue-names</span>=<span class="string">&quot;spring_topic_queue_well&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">ref</span>=<span class="string">&quot;topicListenerWell2&quot;</span> <span class="attr">queue-names</span>=<span class="string">&quot;spring_topic_queue_well2&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">rabbit:listener-container</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="5-2-4-消息监听器"><a href="#5-2-4-消息监听器" class="headerlink" title="5.2.4. 消息监听器"></a>5.2.4. 消息监听器</h3><h4 id="1）队列监听器"><a href="#1）队列监听器" class="headerlink" title="1）队列监听器"></a>1）队列监听器</h4><p>创建 <code>spring-rabbitmq-consumer\src\main\java\com\itheima\rabbitmq\listener\SpringQueueListener.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SpringQueueListener</span> <span class="keyword">implements</span> <span class="title class_">MessageListener</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(Message message)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            System.out.printf(<span class="string">&quot;接收路由名称为：%s，路由键为：%s，队列名为：%s的消息：%s \n&quot;</span>,</span><br><span class="line">                    message.getMessageProperties().getReceivedExchange(),</span><br><span class="line">                    message.getMessageProperties().getReceivedRoutingKey(),</span><br><span class="line">                    message.getMessageProperties().getConsumerQueue(),</span><br><span class="line">                    msg);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="2）广播监听器1"><a href="#2）广播监听器1" class="headerlink" title="2）广播监听器1"></a>2）广播监听器1</h4><p>创建 <code>spring-rabbitmq-consumer\src\main\java\com\itheima\rabbitmq\listener\FanoutListener1.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FanoutListener1</span> <span class="keyword">implements</span> <span class="title class_">MessageListener</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(Message message)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            System.out.printf(<span class="string">&quot;广播监听器1：接收路由名称为：%s，路由键为：%s，队列名为：%s的消息：%s \n&quot;</span>,</span><br><span class="line">                    message.getMessageProperties().getReceivedExchange(),</span><br><span class="line">                    message.getMessageProperties().getReceivedRoutingKey(),</span><br><span class="line">                    message.getMessageProperties().getConsumerQueue(),</span><br><span class="line">                    msg);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="3）广播监听器2"><a href="#3）广播监听器2" class="headerlink" title="3）广播监听器2"></a>3）广播监听器2</h4><p>创建 <code>spring-rabbitmq-consumer\src\main\java\com\itheima\rabbitmq\listener\FanoutListener2.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FanoutListener2</span> <span class="keyword">implements</span> <span class="title class_">MessageListener</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(Message message)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            System.out.printf(<span class="string">&quot;广播监听器2：接收路由名称为：%s，路由键为：%s，队列名为：%s的消息：%s \n&quot;</span>,</span><br><span class="line">                    message.getMessageProperties().getReceivedExchange(),</span><br><span class="line">                    message.getMessageProperties().getReceivedRoutingKey(),</span><br><span class="line">                    message.getMessageProperties().getConsumerQueue(),</span><br><span class="line">                    msg);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4）星号通配符监听器"><a href="#4）星号通配符监听器" class="headerlink" title="4）星号通配符监听器"></a>4）星号通配符监听器</h4><p>创建 <code>spring-rabbitmq-consumer\src\main\java\com\itheima\rabbitmq\listener\TopicListenerStar.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TopicListenerStar</span> <span class="keyword">implements</span> <span class="title class_">MessageListener</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(Message message)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            System.out.printf(<span class="string">&quot;通配符*监听器：接收路由名称为：%s，路由键为：%s，队列名为：%s的消息：%s \n&quot;</span>,</span><br><span class="line">                    message.getMessageProperties().getReceivedExchange(),</span><br><span class="line">                    message.getMessageProperties().getReceivedRoutingKey(),</span><br><span class="line">                    message.getMessageProperties().getConsumerQueue(),</span><br><span class="line">                    msg);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="5）井号通配符监听器"><a href="#5）井号通配符监听器" class="headerlink" title="5）井号通配符监听器"></a>5）井号通配符监听器</h4><p>创建 <code>spring-rabbitmq-consumer\src\main\java\com\itheima\rabbitmq\listener\TopicListenerWell.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TopicListenerWell</span> <span class="keyword">implements</span> <span class="title class_">MessageListener</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(Message message)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            System.out.printf(<span class="string">&quot;通配符#监听器：接收路由名称为：%s，路由键为：%s，队列名为：%s的消息：%s \n&quot;</span>,</span><br><span class="line">                    message.getMessageProperties().getReceivedExchange(),</span><br><span class="line">                    message.getMessageProperties().getReceivedRoutingKey(),</span><br><span class="line">                    message.getMessageProperties().getConsumerQueue(),</span><br><span class="line">                    msg);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="6）井号通配符监听器2"><a href="#6）井号通配符监听器2" class="headerlink" title="6）井号通配符监听器2"></a>6）井号通配符监听器2</h4><p>创建 <code>spring-rabbitmq-consumer\src\main\java\com\itheima\rabbitmq\listener\TopicListenerWell2.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TopicListenerWell2</span> <span class="keyword">implements</span> <span class="title class_">MessageListener</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(Message message)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(message.getBody(), <span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            System.out.printf(<span class="string">&quot;通配符#监听器2：接收路由名称为：%s，路由键为：%s，队列名为：%s的消息：%s \n&quot;</span>,</span><br><span class="line">                    message.getMessageProperties().getReceivedExchange(),</span><br><span class="line">                    message.getMessageProperties().getReceivedRoutingKey(),</span><br><span class="line">                    message.getMessageProperties().getConsumerQueue(),</span><br><span class="line">                    msg);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h1 id="6-Spring-Boot整合RabbitMQ"><a href="#6-Spring-Boot整合RabbitMQ" class="headerlink" title="6. Spring Boot整合RabbitMQ"></a>6. Spring Boot整合RabbitMQ</h1><h2 id="6-1-简介"><a href="#6-1-简介" class="headerlink" title="6.1. 简介"></a>6.1. 简介</h2><p>在Spring项目中，可以使用Spring-Rabbit去操作RabbitMQ<br><a target="_blank" rel="noopener" href="https://github.com/spring-projects/spring-amqp">https://github.com/spring-projects/spring-amqp</a></p>
<p>尤其是在spring boot项目中只需要引入对应的amqp启动器依赖即可，方便的使用RabbitTemplate发送消息，使用注解接收消息。</p>
<p><em>一般在开发过程中</em>：</p>
<p><strong>生产者工程：</strong></p>
<ol>
<li><p>application.yml文件配置RabbitMQ相关信息；</p>
</li>
<li><p>在生产者工程中编写配置类，用于创建交换机和队列，并进行绑定</p>
</li>
<li><p>注入RabbitTemplate对象，通过RabbitTemplate对象发送消息到交换机</p>
</li>
</ol>
<p><strong>消费者工程：</strong></p>
<ol>
<li><p>application.yml文件配置RabbitMQ相关信息</p>
</li>
<li><p>创建消息处理类，用于接收队列中的消息并进行处理</p>
</li>
</ol>
<h2 id="5-2-搭建生产者工程"><a href="#5-2-搭建生产者工程" class="headerlink" title="5.2. 搭建生产者工程"></a>5.2. 搭建生产者工程</h2><h3 id="5-2-1-创建工程-1"><a href="#5-2-1-创建工程-1" class="headerlink" title="5.2.1. 创建工程"></a>5.2.1. 创建工程</h3><p>创建生产者工程springboot-rabbitmq-producer</p>
<p><img src="/myl-mm/assets/1558321303612.png" alt="1556072078816"></p>
<p><img src="/myl-mm/assets/1558321417385.png" alt="1556072084653"></p>
<h3 id="5-2-2-添加依赖-1"><a href="#5-2-2-添加依赖-1" class="headerlink" title="5.2.2. 添加依赖"></a>5.2.2. 添加依赖</h3><p>修改pom.xml文件内容为如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">parent</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.4.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.itheima<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>springboot-rabbitmq-producer<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="5-2-3-启动类"><a href="#5-2-3-启动类" class="headerlink" title="5.2.3. 启动类"></a>5.2.3. 启动类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.SpringApplication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ProducerApplication</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(ProducerApplication.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="5-2-4-配置RabbitMQ"><a href="#5-2-4-配置RabbitMQ" class="headerlink" title="5.2.4. 配置RabbitMQ"></a>5.2.4. 配置RabbitMQ</h3><h4 id="1）配置文件"><a href="#1）配置文件" class="headerlink" title="1）配置文件"></a>1）配置文件</h4><p>创建application.yml，内容如下：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="string">localhost</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">5672</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/itcast</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">heima</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">heima</span></span><br></pre></td></tr></table></figure>



<h4 id="2）绑定交换机和队列"><a href="#2）绑定交换机和队列" class="headerlink" title="2）绑定交换机和队列"></a>2）绑定交换机和队列</h4><p>创建RabbitMQ队列与交换机绑定的配置类com.itheima.rabbitmq.config.RabbitMQConfig</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.amqp.core.*;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RabbitMQConfig</span> &#123;</span><br><span class="line">    <span class="comment">//交换机名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">ITEM_TOPIC_EXCHANGE</span> <span class="operator">=</span> <span class="string">&quot;item_topic_exchange&quot;</span>;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">ITEM_QUEUE</span> <span class="operator">=</span> <span class="string">&quot;item_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//声明交换机</span></span><br><span class="line">    <span class="meta">@Bean(&quot;itemTopicExchange&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Exchange <span class="title function_">topicExchange</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(<span class="literal">true</span>).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//声明队列</span></span><br><span class="line">    <span class="meta">@Bean(&quot;itemQueue&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">itemQueue</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> QueueBuilder.durable(ITEM_QUEUE).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//绑定队列和交换机</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">itemQueueExchange</span><span class="params">(<span class="meta">@Qualifier(&quot;itemQueue&quot;)</span> Queue queue,</span></span><br><span class="line"><span class="params">                                     <span class="meta">@Qualifier(&quot;itemTopicExchange&quot;)</span> Exchange exchange)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(queue).to(exchange).with(<span class="string">&quot;item.#&quot;</span>).noargs();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="5-3-搭建消费者工程"><a href="#5-3-搭建消费者工程" class="headerlink" title="5.3. 搭建消费者工程"></a>5.3. 搭建消费者工程</h2><h3 id="5-3-1-创建工程"><a href="#5-3-1-创建工程" class="headerlink" title="5.3.1. 创建工程"></a>5.3.1. 创建工程</h3><p>创建消费者工程springboot-rabbitmq-consumer</p>
<p><img src="/myl-mm/assets/1558322109359.png" alt="1556073553841"></p>
<p><img src="/myl-mm/assets/1558322192435.png" alt="1556073567786"></p>
<h3 id="5-3-2-添加依赖"><a href="#5-3-2-添加依赖" class="headerlink" title="5.3.2. 添加依赖"></a>5.3.2. 添加依赖</h3><p>修改pom.xml文件内容为如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">parent</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.4.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.itheima<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>springboot-rabbitmq-consumer<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="5-3-3-启动类"><a href="#5-3-3-启动类" class="headerlink" title="5.3.3. 启动类"></a>5.3.3. 启动类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.SpringApplication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConsumerApplication</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SpringApplication.run(ConsumerApplication.class);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="5-3-4-配置RabbitMQ"><a href="#5-3-4-配置RabbitMQ" class="headerlink" title="5.3.4. 配置RabbitMQ"></a>5.3.4. 配置RabbitMQ</h3><p>创建application.yml，内容如下：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="string">localhost</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">5672</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/itcast</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">heima</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">heima</span></span><br></pre></td></tr></table></figure>



<h3 id="5-3-5-消息监听处理类"><a href="#5-3-5-消息监听处理类" class="headerlink" title="5.3.5. 消息监听处理类"></a>5.3.5. 消息监听处理类</h3><p>编写消息监听器com.itheima.rabbitmq.listener.MyListener</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq.listener;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.amqp.rabbit.annotation.RabbitListener;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyListener</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 监听某个队列的消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> message 接收到的消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &quot;item_queue&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">myListener1</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;消费者接收到的消息为：&quot;</span> + message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="5-4-测试"><a href="#5-4-测试" class="headerlink" title="5.4. 测试"></a>5.4. 测试</h2><p>在生产者工程springboot-rabbitmq-producer中创建测试类，发送消息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.rabbitmq;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.itheima.rabbitmq.config.RabbitMQConfig;</span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"><span class="keyword">import</span> org.junit.runner.RunWith;</span><br><span class="line"><span class="keyword">import</span> org.springframework.amqp.rabbit.core.RabbitTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line"><span class="keyword">import</span> org.springframework.test.context.junit4.SpringRunner;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RunWith(SpringRunner.class)</span></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RabbitMQTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test</span><span class="params">()</span>&#123;</span><br><span class="line">        rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, <span class="string">&quot;item.insert&quot;</span>, <span class="string">&quot;商品新增，routing key 为item.insert&quot;</span>);</span><br><span class="line">        rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, <span class="string">&quot;item.update&quot;</span>, <span class="string">&quot;商品修改，routing key 为item.update&quot;</span>);</span><br><span class="line">        rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, <span class="string">&quot;item.delete&quot;</span>, <span class="string">&quot;商品删除，routing key 为item.delete&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>先运行上述测试程序（交换机和队列才能先被声明和绑定），然后启动消费者；在消费者工程springboot-rabbitmq-consumer中控制台查看是否接收到对应消息。</p>
<p>另外；也可以在RabbitMQ的管理控制台中查看到交换机与队列的绑定：</p>
<p><img src="/myl-mm/assets/1556074827222.png" alt="1556074827222"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://gitee.com/tgreen/myl-mm.git">myl</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/tgreen/myl-mm.git/2022/05/09/RabbitMQ%20%E8%AE%B2%E4%B9%89/">https://gitee.com/tgreen/myl-mm.git/2022/05/09/RabbitMQ%20%E8%AE%B2%E4%B9%89/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/tgreen/myl-mm.git" target="_blank">阿毛的博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/myl-mm/tags/RabbitMq/">RabbitMq</a></div><div class="post_share"><div class="social-share" data-image="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/gh/overtrue/share.js@master/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/myl-mm/2022/05/09/RabbitMQ%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/"><img class="prev-cover" src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="onerror=null;src='/myl-mm/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">RabbitMQ 集群</div></div></a></div><div class="next-post pull-right"><a href="/myl-mm/2022/05/09/zookeeper%E8%AE%B2%E4%B9%89md/"><img class="next-cover" src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="onerror=null;src='/myl-mm/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Zookeeper</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/myl-mm/2022/05/09/RabbitMQ%20Windows%20%E5%AE%89%E8%A3%85/" title="RabbitMQ Windows 安装"><img class="cover" src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-09</div><div class="title">RabbitMQ Windows 安装</div></div></a></div><div><a href="/myl-mm/2022/05/09/RabbitMQ%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/" title="RabbitMQ 集群"><img class="cover" src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-09</div><div class="title">RabbitMQ 集群</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/myl-mm/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">myl</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/myl-mm/archives/"><div class="headline">文章</div><div class="length-num">22</div></a><a href="/myl-mm/tags/"><div class="headline">标签</div><div class="length-num">11</div></a><a href="/myl-mm/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><a id="card-info-btn" href="https://gitee.com/tgreen/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎观看，又来一个！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#0-%E5%AD%A6%E4%B9%A0%E7%9B%AE%E6%A0%87"><span class="toc-number">1.</span> <span class="toc-text">0. 学习目标</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#1-%E6%B6%88%E6%81%AF%E4%B8%AD%E9%97%B4%E4%BB%B6%E6%A6%82%E8%BF%B0"><span class="toc-number">2.</span> <span class="toc-text">1. 消息中间件概述</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-%E4%BB%80%E4%B9%88%E6%98%AF%E6%B6%88%E6%81%AF%E4%B8%AD%E9%97%B4%E4%BB%B6"><span class="toc-number">2.1.</span> <span class="toc-text">1.1. 什么是消息中间件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-AMQP-%E5%92%8C-JMS"><span class="toc-number">2.2.</span> <span class="toc-text">1.2. AMQP 和 JMS</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-1-AMQP"><span class="toc-number">2.2.1.</span> <span class="toc-text">1.2.1. AMQP</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-2-JMS"><span class="toc-number">2.2.2.</span> <span class="toc-text">1.2.2. JMS</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-3-AMQP-%E4%B8%8E-JMS-%E5%8C%BA%E5%88%AB"><span class="toc-number">2.2.3.</span> <span class="toc-text">1.2.3. AMQP 与 JMS 区别</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%E4%BA%A7%E5%93%81"><span class="toc-number">2.3.</span> <span class="toc-text">1.3. 消息队列产品</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-4-RabbitMQ"><span class="toc-number">2.4.</span> <span class="toc-text">1.4. RabbitMQ</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-%E5%AE%89%E8%A3%85%E5%8F%8A%E9%85%8D%E7%BD%AERabbitMQ"><span class="toc-number">3.</span> <span class="toc-text">2. 安装及配置RabbitMQ</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-RabbitMQ%E5%85%A5%E9%97%A8"><span class="toc-number">4.</span> <span class="toc-text">3. RabbitMQ入门</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-%E6%90%AD%E5%BB%BA%E7%A4%BA%E4%BE%8B%E5%B7%A5%E7%A8%8B"><span class="toc-number">4.1.</span> <span class="toc-text">3.1. 搭建示例工程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-1-%E5%88%9B%E5%BB%BA%E5%B7%A5%E7%A8%8B"><span class="toc-number">4.1.1.</span> <span class="toc-text">3.1.1. 创建工程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-2-%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-number">4.1.2.</span> <span class="toc-text">3.1.2. 添加依赖</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2-%E7%BC%96%E5%86%99%E7%94%9F%E4%BA%A7%E8%80%85"><span class="toc-number">4.2.</span> <span class="toc-text">3.2. 编写生产者</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-3-%E7%BC%96%E5%86%99%E6%B6%88%E8%B4%B9%E8%80%85"><span class="toc-number">4.3.</span> <span class="toc-text">3.3. 编写消费者</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">4.4.</span> <span class="toc-text">3.4. 小结</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-AMQP"><span class="toc-number">5.</span> <span class="toc-text">4. AMQP</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1-%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5%E4%BB%8B%E7%BB%8D"><span class="toc-number">5.1.</span> <span class="toc-text">4.1. 相关概念介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-2-RabbitMQ%E8%BF%90%E8%BD%AC%E6%B5%81%E7%A8%8B"><span class="toc-number">5.2.</span> <span class="toc-text">4.2. RabbitMQ运转流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-3-%E7%94%9F%E4%BA%A7%E8%80%85%E6%B5%81%E8%BD%AC%E8%BF%87%E7%A8%8B%E8%AF%B4%E6%98%8E"><span class="toc-number">5.3.</span> <span class="toc-text">4.3. 生产者流转过程说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-4-%E6%B6%88%E8%B4%B9%E8%80%85%E6%B5%81%E8%BD%AC%E8%BF%87%E7%A8%8B%E8%AF%B4%E6%98%8E"><span class="toc-number">5.4.</span> <span class="toc-text">4.4. 消费者流转过程说明</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-RabbitMQ%E5%B7%A5%E4%BD%9C%E6%A8%A1%E5%BC%8F"><span class="toc-number">6.</span> <span class="toc-text">5. RabbitMQ工作模式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1-Work-queues%E5%B7%A5%E4%BD%9C%E9%98%9F%E5%88%97%E6%A8%A1%E5%BC%8F"><span class="toc-number">6.1.</span> <span class="toc-text">4.1. Work queues工作队列模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">6.1.1.</span> <span class="toc-text">4.1.1. 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">6.1.2.</span> <span class="toc-text">4.1.2. 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E7%94%9F%E4%BA%A7%E8%80%85"><span class="toc-number">6.1.2.1.</span> <span class="toc-text">1）生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%851"><span class="toc-number">6.1.2.2.</span> <span class="toc-text">2）消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%852"><span class="toc-number">6.1.2.3.</span> <span class="toc-text">3）消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">6.1.3.</span> <span class="toc-text">4.1.3. 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">6.1.4.</span> <span class="toc-text">4.1.4. 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-2-%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F%E7%B1%BB%E5%9E%8B"><span class="toc-number">6.2.</span> <span class="toc-text">4.2. 订阅模式类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-3-Publish-x2F-Subscribe%E5%8F%91%E5%B8%83%E4%B8%8E%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F"><span class="toc-number">6.3.</span> <span class="toc-text">4.3. Publish&#x2F;Subscribe发布与订阅模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">6.3.1.</span> <span class="toc-text">4.3.1. 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">6.3.2.</span> <span class="toc-text">4.3.2. 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E7%94%9F%E4%BA%A7%E8%80%85-1"><span class="toc-number">6.3.2.1.</span> <span class="toc-text">1）生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%851-1"><span class="toc-number">6.3.2.2.</span> <span class="toc-text">2）消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%852-1"><span class="toc-number">6.3.2.3.</span> <span class="toc-text">3）消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">6.3.3.</span> <span class="toc-text">4.3.3. 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">6.3.4.</span> <span class="toc-text">4.3.4. 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-4-Routing%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%BC%8F"><span class="toc-number">6.4.</span> <span class="toc-text">4.4. Routing路由模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">6.4.1.</span> <span class="toc-text">4.4.1. 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">6.4.2.</span> <span class="toc-text">4.4.2. 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E7%94%9F%E4%BA%A7%E8%80%85-2"><span class="toc-number">6.4.2.1.</span> <span class="toc-text">1）生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%851-2"><span class="toc-number">6.4.2.2.</span> <span class="toc-text">2）消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%852-2"><span class="toc-number">6.4.2.3.</span> <span class="toc-text">3）消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">6.4.3.</span> <span class="toc-text">4.4.3. 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">6.4.4.</span> <span class="toc-text">4.4.4. 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-5-Topics%E9%80%9A%E9%85%8D%E7%AC%A6%E6%A8%A1%E5%BC%8F"><span class="toc-number">6.5.</span> <span class="toc-text">4.5. Topics通配符模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">6.5.1.</span> <span class="toc-text">4.5.1. 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">6.5.2.</span> <span class="toc-text">4.5.2. 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E7%94%9F%E4%BA%A7%E8%80%85-3"><span class="toc-number">6.5.2.1.</span> <span class="toc-text">1）生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%851-3"><span class="toc-number">6.5.2.2.</span> <span class="toc-text">2）消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89%E6%B6%88%E8%B4%B9%E8%80%852-3"><span class="toc-number">6.5.2.3.</span> <span class="toc-text">3）消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">6.5.3.</span> <span class="toc-text">4.5.3. 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">6.5.4.</span> <span class="toc-text">4.5.4. 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-6-%E6%A8%A1%E5%BC%8F%E6%80%BB%E7%BB%93"><span class="toc-number">6.6.</span> <span class="toc-text">4.6. 模式总结</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-Spring-%E6%95%B4%E5%90%88RabbitMQ"><span class="toc-number">7.</span> <span class="toc-text">5. Spring 整合RabbitMQ</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#5-1-%E6%90%AD%E5%BB%BA%E7%94%9F%E4%BA%A7%E8%80%85%E5%B7%A5%E7%A8%8B"><span class="toc-number">7.1.</span> <span class="toc-text">5.1. 搭建生产者工程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-1-%E5%88%9B%E5%BB%BA%E5%B7%A5%E7%A8%8B"><span class="toc-number">7.1.1.</span> <span class="toc-text">5.1.1. 创建工程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-2-%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-number">7.1.2.</span> <span class="toc-text">5.1.2. 添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-3-%E9%85%8D%E7%BD%AE%E6%95%B4%E5%90%88"><span class="toc-number">7.1.3.</span> <span class="toc-text">5.1.3. 配置整合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-4-%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF"><span class="toc-number">7.1.4.</span> <span class="toc-text">5.1.4. 发送消息</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-2-%E6%90%AD%E5%BB%BA%E6%B6%88%E8%B4%B9%E8%80%85%E5%B7%A5%E7%A8%8B"><span class="toc-number">7.2.</span> <span class="toc-text">5.2. 搭建消费者工程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-1-%E5%88%9B%E5%BB%BA%E5%B7%A5%E7%A8%8B"><span class="toc-number">7.2.1.</span> <span class="toc-text">5.2.1. 创建工程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-2-%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-number">7.2.2.</span> <span class="toc-text">5.2.2. 添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-3-%E9%85%8D%E7%BD%AE%E6%95%B4%E5%90%88"><span class="toc-number">7.2.3.</span> <span class="toc-text">5.2.3. 配置整合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-4-%E6%B6%88%E6%81%AF%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">7.2.4.</span> <span class="toc-text">5.2.4. 消息监听器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E9%98%9F%E5%88%97%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">7.2.4.1.</span> <span class="toc-text">1）队列监听器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E5%B9%BF%E6%92%AD%E7%9B%91%E5%90%AC%E5%99%A81"><span class="toc-number">7.2.4.2.</span> <span class="toc-text">2）广播监听器1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%EF%BC%89%E5%B9%BF%E6%92%AD%E7%9B%91%E5%90%AC%E5%99%A82"><span class="toc-number">7.2.4.3.</span> <span class="toc-text">3）广播监听器2</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%EF%BC%89%E6%98%9F%E5%8F%B7%E9%80%9A%E9%85%8D%E7%AC%A6%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">7.2.4.4.</span> <span class="toc-text">4）星号通配符监听器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%EF%BC%89%E4%BA%95%E5%8F%B7%E9%80%9A%E9%85%8D%E7%AC%A6%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">7.2.4.5.</span> <span class="toc-text">5）井号通配符监听器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6%EF%BC%89%E4%BA%95%E5%8F%B7%E9%80%9A%E9%85%8D%E7%AC%A6%E7%9B%91%E5%90%AC%E5%99%A82"><span class="toc-number">7.2.4.6.</span> <span class="toc-text">6）井号通配符监听器2</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#6-Spring-Boot%E6%95%B4%E5%90%88RabbitMQ"><span class="toc-number">8.</span> <span class="toc-text">6. Spring Boot整合RabbitMQ</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#6-1-%E7%AE%80%E4%BB%8B"><span class="toc-number">8.1.</span> <span class="toc-text">6.1. 简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-2-%E6%90%AD%E5%BB%BA%E7%94%9F%E4%BA%A7%E8%80%85%E5%B7%A5%E7%A8%8B"><span class="toc-number">8.2.</span> <span class="toc-text">5.2. 搭建生产者工程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-1-%E5%88%9B%E5%BB%BA%E5%B7%A5%E7%A8%8B-1"><span class="toc-number">8.2.1.</span> <span class="toc-text">5.2.1. 创建工程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-2-%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96-1"><span class="toc-number">8.2.2.</span> <span class="toc-text">5.2.2. 添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-3-%E5%90%AF%E5%8A%A8%E7%B1%BB"><span class="toc-number">8.2.3.</span> <span class="toc-text">5.2.3. 启动类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-4-%E9%85%8D%E7%BD%AERabbitMQ"><span class="toc-number">8.2.4.</span> <span class="toc-text">5.2.4. 配置RabbitMQ</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%EF%BC%89%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">8.2.4.1.</span> <span class="toc-text">1）配置文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%89%E7%BB%91%E5%AE%9A%E4%BA%A4%E6%8D%A2%E6%9C%BA%E5%92%8C%E9%98%9F%E5%88%97"><span class="toc-number">8.2.4.2.</span> <span class="toc-text">2）绑定交换机和队列</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-3-%E6%90%AD%E5%BB%BA%E6%B6%88%E8%B4%B9%E8%80%85%E5%B7%A5%E7%A8%8B"><span class="toc-number">8.3.</span> <span class="toc-text">5.3. 搭建消费者工程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-1-%E5%88%9B%E5%BB%BA%E5%B7%A5%E7%A8%8B"><span class="toc-number">8.3.1.</span> <span class="toc-text">5.3.1. 创建工程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-2-%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="toc-number">8.3.2.</span> <span class="toc-text">5.3.2. 添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-3-%E5%90%AF%E5%8A%A8%E7%B1%BB"><span class="toc-number">8.3.3.</span> <span class="toc-text">5.3.3. 启动类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-4-%E9%85%8D%E7%BD%AERabbitMQ"><span class="toc-number">8.3.4.</span> <span class="toc-text">5.3.4. 配置RabbitMQ</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-5-%E6%B6%88%E6%81%AF%E7%9B%91%E5%90%AC%E5%A4%84%E7%90%86%E7%B1%BB"><span class="toc-number">8.3.5.</span> <span class="toc-text">5.3.5. 消息监听处理类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-4-%E6%B5%8B%E8%AF%95"><span class="toc-number">8.4.</span> <span class="toc-text">5.4. 测试</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/myl-mm/2022/05/09/RabbitMQ%20Windows%20%E5%AE%89%E8%A3%85/" title="RabbitMQ Windows 安装"><img src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="this.onerror=null;this.src='/myl-mm/img/404.jpg'" alt="RabbitMQ Windows 安装"/></a><div class="content"><a class="title" href="/myl-mm/2022/05/09/RabbitMQ%20Windows%20%E5%AE%89%E8%A3%85/" title="RabbitMQ Windows 安装">RabbitMQ Windows 安装</a><time datetime="2022-05-09T09:04:30.600Z" title="发表于 2022-05-09 17:04:30">2022-05-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/myl-mm/2022/05/09/gateway%E5%86%85%E7%BD%AE%E8%BF%87%E6%BB%A4%E5%99%A8%E5%B7%A5%E5%8E%82/" title="Spring Cloud Gateway 内置的过滤器工厂"><img src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="this.onerror=null;this.src='/myl-mm/img/404.jpg'" alt="Spring Cloud Gateway 内置的过滤器工厂"/></a><div class="content"><a class="title" href="/myl-mm/2022/05/09/gateway%E5%86%85%E7%BD%AE%E8%BF%87%E6%BB%A4%E5%99%A8%E5%B7%A5%E5%8E%82/" title="Spring Cloud Gateway 内置的过滤器工厂">Spring Cloud Gateway 内置的过滤器工厂</a><time datetime="2022-05-09T09:04:19.065Z" title="发表于 2022-05-09 17:04:19">2022-05-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/myl-mm/2022/05/09/Turbine%E6%90%AD%E5%BB%BA%E6%AD%A5%E9%AA%A4/" title="Turbine"><img src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="this.onerror=null;this.src='/myl-mm/img/404.jpg'" alt="Turbine"/></a><div class="content"><a class="title" href="/myl-mm/2022/05/09/Turbine%E6%90%AD%E5%BB%BA%E6%AD%A5%E9%AA%A4/" title="Turbine">Turbine</a><time datetime="2022-05-09T09:04:13.000Z" title="发表于 2022-05-09 17:04:13">2022-05-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/myl-mm/2022/05/09/Eureka%20%E5%85%A8%E9%83%A8%E9%85%8D%E7%BD%AE%20/" title="Euraka配置详解"><img src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="this.onerror=null;this.src='/myl-mm/img/404.jpg'" alt="Euraka配置详解"/></a><div class="content"><a class="title" href="/myl-mm/2022/05/09/Eureka%20%E5%85%A8%E9%83%A8%E9%85%8D%E7%BD%AE%20/" title="Euraka配置详解">Euraka配置详解</a><time datetime="2022-05-09T09:03:49.699Z" title="发表于 2022-05-09 17:03:49">2022-05-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/myl-mm/2022/05/09/01-Springboot-day01/" title="springBootday01"><img src="https://itcast-haoke-myl.oss-cn-beijing.aliyuncs.com/images/2022/04/13/cat1.jpg" onerror="this.onerror=null;this.src='/myl-mm/img/404.jpg'" alt="springBootday01"/></a><div class="content"><a class="title" href="/myl-mm/2022/05/09/01-Springboot-day01/" title="springBootday01">springBootday01</a><time datetime="2022-05-09T09:03:15.476Z" title="发表于 2022-05-09 17:03:15">2022-05-09</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By myl</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/myl-mm/js/utils.js"></script><script src="/myl-mm/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>